// ------------------------------------------数据逻辑
const data = {
	lrc: lrc,
	lrcArr: []
}

/**
 * 格式化歌词，格式化对象结果为：{time:'时间',word:'歌词'}
 */
function parseLrc() {
	const lrcLines = data.lrc.split('\n')
	lrcLines.forEach(str => {
		const parts = str.split(']')
		const lrcObj = {
			time: parseTime(parts[0].substring(1)),
			word: parts[1]
		}
		data.lrcArr.push(lrcObj)
	})
	console.log(data.lrcArr);
}

/**
 * 格式化时间
 * @param {string} timeStr
 * @returns {number} newTime
 */
function parseTime(timeStr) {
	const parts = timeStr.split(':')
	return (parts[0] * 60 + (+parts[1])).toFixed(2)
}

parseLrc()


// ----------------------------------------------------------界面逻辑
// 界面逻辑中需要使用的dom节点数据
const doms = {
	lrcBox:document.querySelector('.lrc_box'),
	audio: document.querySelector('.player_box'),
	ul: document.querySelector('.lrc_list')
}
// ui逻辑中需要的操作数据
const uiData = {
	currentIndex:-1,
	lrcBoxHeight:doms.lrcBox.clientHeight,
	liHeight:0
}

/**
 * 初始化页面
 */
function initPage() {
	// 创建文档片段
	const frag = document.createDocumentFragment()
	data.lrcArr.forEach(lrc => {
		const li = document.createElement('li')
		li.classList.add('lrc_word')
		li.textContent = lrc.word
		frag.appendChild(li)
	})
	doms.ul.appendChild(frag)
	uiData.liHeight = doms.ul.children[0].clientHeight
}
/**
 * 找到需要高亮的歌词下标
 */
function findCurrentIndex() {
	const currentTime = doms.audio.currentTime
	for (let index in data.lrcArr) {
		const lrc = data.lrcArr[index]
		if (lrc.time > currentTime) {
			uiData.currentIndex = index - 1
			return;
		}
	}
	uiData.currentIndex = data.lrcArr.length-1
}

/**
 * 高亮显示当前播放的歌词
 */
function showLrc(){
	findCurrentIndex()
	const oldLi = doms.ul.querySelector('.lrc_word_active')
	oldLi?oldLi.classList.remove('lrc_word_active'):1
	if(uiData.currentIndex>-1){
		const li = doms.ul.children[uiData.currentIndex]
		li.classList.add('lrc_word_active')
	};
}

/**
 * 添加歌词滚动效果
 */
function setUlOffset(){
	showLrc()
	let height = uiData.liHeight*uiData.currentIndex+uiData.liHeight/2 - uiData.lrcBoxHeight/2
	if(height < 0){
		height = 0
	}
	doms.ul.style.transform = `translateY(-${height}px)`
	console.log(height);
}

initPage()

// --------------------------------------------------------------事件逻辑
doms.audio.addEventListener('timeupdate',function(){
	setUlOffset()
})

document.addEventListener('keydown',function(e){
	if(e.keyCode === 37){
		doms.audio.currentTime -= 5
	}else if(e.keyCode === 39){
		doms.audio.currentTime += 5
	}
})
